'use strict'

const Controller = require('egg').Controller
const jwt = require('jsonwebtoken')

class HomeController extends Controller {
  //登录
  async login() {
    const { ctx } = this
    const { user, pas, code } = ctx.request.body
    const result = await this.app.mysql.get('login', { user: user, pas: pas })
    if (result) {
      const token = jwt.sign({ ...result }, '2003', { expiresIn: '1d' })
      ctx.body = {
        code: 200,
        message: '登录成功',
        token,
      }
    } else {
      ctx.body = {
        code: 401,
        message: '登录失败',
      }
    }
  }

  //添加乘客
  async addcar() {
    const { ctx } = this
    ctx.body = {
      code: 200,
      message: '成功',
    }
  }

  //用户数据
  async loginlists() {
    const { ctx } = this
    const list = await this.app.mysql.select('login')
    ctx.body = {
      code: 200,
      message: '用户数据请求成功',
      list,
    }
  }

  //注册
  async sign() {
    const { ctx } = this
    const { user, pas, authid, name, authimg } = ctx.request.body
    const res = await this.app.mysql.get('login', { user, pas })
    if (res) {
      ctx.body = {
        code: 404,
        msg: '注册失败，账号已存在',
      }
    } else {
      const list = await this.app.mysql.insert('login', {
        user,
        pas,
        authid: '10002',
        name: '访客',
        authimg:
          'https://img1.baidu.com/it/u=374933543,4069338443&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=500',
      })
      ctx.body = {
        code: 200,
        msg: '注册成功',
      }
    }
  }

  //修改密码
  async updatalogin() {
    const { ctx } = this
    const { pas, checkPass, userpas, id } = ctx.request.body
    console.log(pas, checkPass, userpas, id)
    const row = {
      id,
      pas: `${pas}`,
    }
    const result = await this.app.mysql.update('login', row) // 更新 posts 表中的记录
    if (result.affectedRows === 1) {
      ctx.body = {
        code: 200,
        msg: '密码修改成功',
      }
    } else {
      ctx.body = {
        code: 400,
        msg: '密码修改失败',
      }
    }
  }
}

module.exports = HomeController
